//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package admin_client_cfg_api_serv

import (
	"context"
	"time"

	"atomgit.com/openlinksaas-org/api-server/admin_api_serv/admin_common"
	"atomgit.com/openlinksaas-org/api-server/config"
	"atomgit.com/openlinksaas-org/api-server/dao"
	"atomgit.com/openlinksaas-org/api-server/dao/client_cfg_dao"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/client_cfg_api"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/mongo"
)

type ClientCfgAdminApiImpl struct {
	client_cfg_api.UnimplementedClientCfgAdminApiServer
	adminCfg *config.AdminCfg
}

func NewClientCfgAdminApiImpl(adminCfg *config.AdminCfg) *ClientCfgAdminApiImpl {
	return &ClientCfgAdminApiImpl{adminCfg: adminCfg}
}

func (apiImpl *ClientCfgAdminApiImpl) ListExtraMenu(ctx context.Context, req *client_cfg_api.AdminListExtraMenuRequest) (*client_cfg_api.AdminListExtraMenuResponse, error) {
	emptyList := []*client_cfg_api.ExtraMenuItem{}

	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &client_cfg_api.AdminListExtraMenuResponse{
			Code:     client_cfg_api.AdminListExtraMenuResponse_CODE_WRONG_SESSION,
			ErrMsg:   "会话不存在",
			MenuList: emptyList,
		}, nil
	}
	if !sess.AuthOk {
		return &client_cfg_api.AdminListExtraMenuResponse{
			Code:     client_cfg_api.AdminListExtraMenuResponse_CODE_NOT_AUTH,
			ErrMsg:   "未授权会话",
			MenuList: emptyList,
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.MenuPerm.Read {
		return &client_cfg_api.AdminListExtraMenuResponse{
			Code:     client_cfg_api.AdminListExtraMenuResponse_CODE_NO_PERMISSION,
			ErrMsg:   "没有权限",
			MenuList: emptyList,
		}, nil
	}

	menuItemList, err := client_cfg_dao.ExtraMenuDao.List(ctx)
	if err != nil {
		return nil, err
	}

	menuList := []*client_cfg_api.ExtraMenuItem{}
	for _, menuItem := range menuItemList {
		menuList = append(menuList, menuItem.ToExtraMenuItem())
	}
	return &client_cfg_api.AdminListExtraMenuResponse{
		Code:     client_cfg_api.AdminListExtraMenuResponse_CODE_OK,
		MenuList: menuList,
	}, nil
}

func (apiImpl *ClientCfgAdminApiImpl) AddExtraMenu(ctx context.Context, req *client_cfg_api.AdminAddExtraMenuRequest) (*client_cfg_api.AdminAddExtraMenuResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &client_cfg_api.AdminAddExtraMenuResponse{
			Code:   client_cfg_api.AdminAddExtraMenuResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &client_cfg_api.AdminAddExtraMenuResponse{
			Code:   client_cfg_api.AdminAddExtraMenuResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.MenuPerm.Add {
		return &client_cfg_api.AdminAddExtraMenuResponse{
			Code:   client_cfg_api.AdminAddExtraMenuResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	menuId := uuid.NewString()
	nowTime := time.Now().UnixNano() / 1e6

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = client_cfg_dao.ExtraMenuDao.Insert(sessCtx, &client_cfg_dao.ExtraMenuDbItem{
			MenuId:        menuId,
			Name:          req.Name,
			Url:           req.Url,
			TimeStamp:     nowTime,
			Weight:        req.Weight,
			MainMenu:      req.MainMenu,
			OpenInBrowser: req.OpenInBrowser,
		})
		if err != nil {
			return nil, err
		}
		return &client_cfg_api.AdminAddExtraMenuResponse{
			Code:   client_cfg_api.AdminAddExtraMenuResponse_CODE_OK,
			MenuId: menuId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*client_cfg_api.AdminAddExtraMenuResponse), nil
}

func (apiImpl *ClientCfgAdminApiImpl) RemoveExtraMenu(ctx context.Context, req *client_cfg_api.AdminRemoveExtraMenuRequest) (*client_cfg_api.AdminRemoveExtraMenuResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &client_cfg_api.AdminRemoveExtraMenuResponse{
			Code:   client_cfg_api.AdminRemoveExtraMenuResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &client_cfg_api.AdminRemoveExtraMenuResponse{
			Code:   client_cfg_api.AdminRemoveExtraMenuResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.MenuPerm.Remove {
		return &client_cfg_api.AdminRemoveExtraMenuResponse{
			Code:   client_cfg_api.AdminRemoveExtraMenuResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := client_cfg_dao.ExtraMenuDao.Exist(ctx, req.MenuId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &client_cfg_api.AdminRemoveExtraMenuResponse{
			Code:   client_cfg_api.AdminRemoveExtraMenuResponse_CODE_NO_MENU,
			ErrMsg: "菜单项不存在",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = client_cfg_dao.ExtraMenuDao.Remove(sessCtx, req.MenuId)
		if err != nil {
			return nil, err
		}
		return &client_cfg_api.AdminRemoveExtraMenuResponse{
			Code: client_cfg_api.AdminRemoveExtraMenuResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*client_cfg_api.AdminRemoveExtraMenuResponse), nil
}

func (apiImpl *ClientCfgAdminApiImpl) UpdateExtraMenu(ctx context.Context, req *client_cfg_api.AdminUpdateExtraMenuRequest) (*client_cfg_api.AdminUpdateExtraMenuResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &client_cfg_api.AdminUpdateExtraMenuResponse{
			Code:   client_cfg_api.AdminUpdateExtraMenuResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &client_cfg_api.AdminUpdateExtraMenuResponse{
			Code:   client_cfg_api.AdminUpdateExtraMenuResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.MenuPerm.Update {
		return &client_cfg_api.AdminUpdateExtraMenuResponse{
			Code:   client_cfg_api.AdminUpdateExtraMenuResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := client_cfg_dao.ExtraMenuDao.Exist(ctx, req.MenuId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &client_cfg_api.AdminUpdateExtraMenuResponse{
			Code:   client_cfg_api.AdminUpdateExtraMenuResponse_CODE_NO_MENU,
			ErrMsg: "菜单项不存在",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = client_cfg_dao.ExtraMenuDao.Update(sessCtx, &client_cfg_dao.ExtraMenuDbItem{
			MenuId:        req.MenuId,
			Name:          req.Name,
			Url:           req.Url,
			TimeStamp:     time.Now().UnixNano() / 1e6,
			Weight:        req.Weight,
			MainMenu:      req.MainMenu,
			OpenInBrowser: req.OpenInBrowser,
		})
		if err != nil {
			return nil, err
		}
		return &client_cfg_api.AdminUpdateExtraMenuResponse{
			Code: client_cfg_api.AdminUpdateExtraMenuResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*client_cfg_api.AdminUpdateExtraMenuResponse), nil
}
